package com.vf.admin.platform.controller;

import com.vf.admin.common.BaseController;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.platform.dto.MenuElementDto;
import com.vf.admin.platform.dto.RoleMenuDto;
import com.vf.admin.platform.entity.*;
import com.vf.admin.platform.service.*;
import com.vf.admin.utils.RecuUtils;
import com.vf.admin.utils.StringEx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 平台角色
 */
@Controller
@RequestMapping(value="/role")
public class RoleController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private ElementService elementService;
    @Autowired
    private RoleMenuElementService roleMenuElementService;



    /**
     * 获取所有角色列表信息
     * @param pageBean 分页对象
     * @param role 角色
     * @return
     */
    @RequestMapping("/list")
    public String list(SplitPageBean pageBean,Role role){
        try {
            Map<String, Object> paraMap = new HashMap<String, Object>();
            if(role!=null){
                paraMap.put("name",role.getName());
                paraMap.put("states",role.getStates());
            }else{
                role = new Role();
            }
            SplitPageBean splitPage = new SplitPageBean(pageBean.getPageIndex(),pageBean.getPageSize());
            List<Role> list = roleService.findList(paraMap,splitPage);
            Map<Integer,String> shiFouStateMap = Constants.getShiFouStateMap();
            request.setAttribute("role",role);
            request.setAttribute("list",list);
            request.setAttribute("splitPage",splitPage);
            request.setAttribute("shiFouStateMap",shiFouStateMap);
            return this.sucess("/web/platform/role/list");
        }catch(Exception e){
            logger.error("查询角色列表异常",e);
            return this.error("操作异常，请联系管理员");
        }
    }

    /**
     * 获取角色详情
     * @return
     */
    @RequestMapping("/detail")
    public String detail(Integer id){
        try{
//            if(id.intValue()!=100){
//                return this.error("id不等于100");
//            }
            Role role = new Role();
            if(id!=null && id>0){
                role = roleService.get(id);
            }
            Map<Integer,String> shiFouStateMap = Constants.getShiFouStateMap();
            request.setAttribute("role",role);
            request.setAttribute("shiFouStateMap",shiFouStateMap);
            return this.sucess("/web/platform/role/edit");
        }catch(Exception e){
            logger.error("查询角色列表异常", e);
            return this.error("查询角色列表异常");
        }
    }

    /**
     * 添加修改角色
     *     role 角色对象
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public Result addOrUpdate(Role role){
        System.out.println("aaaaaaaaaaaaaaaaaaa"+role);
        if(StringEx.isNull(role.getName())){
            return this.errorJSON("名称不能为空!");
        }
        if(StringEx.isNullOrLing(role.getSorts())){
            return this.errorJSON("排序值不能为空!");
        }
        if(StringEx.isNull(role.getComments())){
            return this.errorJSON("备注不能为空!");
        }
        if(role.getId() == null || role.getId()<=0){
            role.setStates(role.getStates() == null ? Constants.shiFou_STATE_FOU : role.getStates());
            roleService.saveOrUpdate(role);
        }else{
            Role roleBf = roleService.get(role.getId());
            roleBf.setName(role.getName());
            roleBf.setComments(role.getComments());
            roleBf.setSorts(role.getSorts());
            if(roleBf.getIsrootrole()!=null && roleBf.getIsrootrole() == 1){
            }else{
                roleBf.setStates(role.getStates() == null ? Constants.shiFou_STATE_FOU : role.getStates());
            }
            roleService.saveOrUpdate(roleBf);
        }
        return this.sucessJSON("操作成功！");
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping("/del")
    @ResponseBody
    public Result del(String idArray){
        try{
            if(StringEx.isNull(idArray)){
                return this.errorJSON("用户编号不能为空!");
            }
            String[] userIdArray = idArray.split(",");
            if(userIdArray!=null && userIdArray.length>0){
                for(String id : userIdArray){
                    if(StringEx.isNull(id)){
                        continue;
                    }
                    Role role = roleService.get(Integer.valueOf(id));
                    if(role!=null &&  role.getIsrootrole()!=null && role.getIsrootrole().intValue() == 1){
                        //最高权限用户不允许删除
                        return this.errorJSON("最高权限用户不允许删除!");
                    }else{
                        roleService.del(role.getId());
                    }
                }
            }
            return this.sucess();
        }catch(Exception e){
            logger.error("删除平台角色信息异常", e);
            return this.errorJSON("删除平台角色信息异常，请联系管理员");
        }
    }

    /**
     * 获取该角色下的菜单权限和菜单下的标签权限
     * @param id   角色id
     * @return
     */
    @RequestMapping("/roleMenuList")
    public String roleMenuList(Integer id){
        try{
            List<Menu> menuList = new ArrayList<Menu>();

            if(StringEx.isNullOrLing(id)){
                return this.error("角色编号不能为空");
            }

            Role role = roleService.get(id);

            //当前角色拥有的菜单列表
            Map<String,Object> paraMap = new HashMap<>();
            paraMap.put("roleid",id);
            List<RoleMenu> userRoleList = roleMenuService.findList(paraMap);
            Map<Integer,Integer> userRoleMap = new HashMap<Integer,Integer>();
            if(userRoleList!=null && userRoleList.size()>0){
                for(RoleMenu roleMenu : userRoleList){
                    Integer menuId = roleMenu.getMenuid();
                    userRoleMap.put(menuId.intValue(),roleMenu.getRoleid());
                }
            }

            //获取所有的标签列表
            paraMap.clear();
            List<Element> elementList = elementService.findList(paraMap);

            Map<String,Element> menuElementMap = new HashMap<String,Element>();
            if(elementList!=null && elementList.size()>0){
                for(Element element : elementList){
                    menuElementMap.put(""+element.getMenuid()+"_"+element.getId(),element);
                }
            }

            //获取当前角色下拥有的所有的标签列表
            paraMap.clear();
            paraMap.put("roleid",id);
            List<RoleMenuElement> roleMenuElementList = roleMenuElementService.findList(paraMap);

            Map<String,Integer> roleMenuElementMap = new HashMap<String,Integer>();
            if(roleMenuElementList!=null && roleMenuElementList.size()>0){
                for(RoleMenuElement roleMenuElement : roleMenuElementList){
                    roleMenuElementMap.put(""+roleMenuElement.getRoleid()+"_"+roleMenuElement.getMenuid()+"_"+roleMenuElement.getElementid(),roleMenuElement.getElementid());
                }
            }

            Map<String,Object> resultMap = new HashMap<String,Object>();
            //所有菜单列表
            paraMap.clear();
            List<Menu> list = menuService.findList(paraMap);

            if(list!=null && list.size()>0){
                for(Menu menu : list){
//                    if(menu.getId() == 1){
//                        continue;
//                    }
                    Integer menuId = menu.getId();
                    Integer roleId = userRoleMap.get(menuId.intValue());
                    menu.setSpread(true);
//                    if(menu.getPid() == -1){
//                        menu.setPid(0);
//                    }
                    if(roleId!=null && roleId.intValue() >0 ){
                        menu.setChecked(true);
                    }else{
                        menu.setChecked(false);
                    }
                    if(menu.getTitle()!=null){
                        menu.setTitle(menu.getTitle().trim());
                    }else{
                        menu.setTitle("");
                    }
                    if(elementList!=null && elementList.size()>0){
                        for(Element element : elementList){
                            //判断该菜单下的所有标签是否存在，如果存在是否已经赋予该标签权限 roleMenuElementMap

                            Element elementNew = menuElementMap.get(""+menu.getId()+"_"+element.getId());
                            if(elementNew!=null && elementNew.getId()!=null && elementNew.getId().intValue()>0){
                                System.out.println(""+menu.getId()+"_"+element.getId());
                                System.out.println(menu.getTitle());
                                if(menu.getElementList() == null){
                                    List<Element> elementsList =  new ArrayList<Element>();
                                    menu.setElementList(elementsList);
                                }
                                Integer elementValue = roleMenuElementMap.get(""+id+"_"+elementNew.getMenuid()+"_"+elementNew.getId());

                                Element elementSelect = new Element();
                                if( elementValue !=null && elementValue.intValue() ==  elementNew.getId().intValue()){
                                    elementSelect.setChecked(true);
                                }else{
                                    elementSelect.setChecked(false);
                                }
                                elementSelect.setId(elementNew.getId());
                                elementSelect.setTitle(elementNew.getTitle());
                                elementSelect.setMenuid(elementNew.getMenuid());
                                menu.getElementList().add(elementSelect);
                            }
                        }
                    }
                }
            }
//            menuList = RecuUtils.getInstance().findMenuList(list,-1);

            request.setAttribute("role",role);
            request.setAttribute("list",list);
            return this.sucess("/web/platform/role/rolemenu");
        }catch(Exception e){
            e.printStackTrace();
            logger.error("获取该角色下的菜单权限异常", e);
            e.printStackTrace();
            return this.error("获取该角色下的菜单权限异常");
        }
    }


    /**
     * 保存角色的菜单权限
     * @param roleMenuDto
     * @return
     */
    @RequestMapping("/saveRoleMenu")
    @ResponseBody
    public Result saveRoleMenu(RoleMenuDto roleMenuDto){
        try{
            Map<String,Object> map = new HashMap<>();
            if(StringEx.isNullOrLing(roleMenuDto.getRoleid())){
                return this.errorJSON("角色编号不能为空");
            }
            Role role = roleService.get(roleMenuDto.getRoleid());
            if(role == null ||StringEx.isNullOrLing(role.getId())){
                return this.errorJSON("角色信息不存在");
            }
            List<RoleMenu> roleMenuList = new ArrayList<RoleMenu>();
            List<RoleMenuElement> roleMenuElementsList = new ArrayList<RoleMenuElement>();
            if(roleMenuDto.getMenuidArray()!=null && roleMenuDto.getMenuidArray().size()>0){
                for(MenuElementDto menuElementDto : roleMenuDto.getMenuidArray()){
                    RoleMenu roleMenuNew = new RoleMenu();
                    roleMenuNew.setRoleid(roleMenuDto.getRoleid());
                    roleMenuNew.setMenuid(menuElementDto.getMenuid());
                    roleMenuList.add(roleMenuNew);
                    if(menuElementDto.getElementidList()!=null && menuElementDto.getElementidList().size()>0){
                        for(Integer elementid : menuElementDto.getElementidList()){
                            RoleMenuElement roleMenuElementNew = new RoleMenuElement();
                            roleMenuElementNew.setRoleid(roleMenuDto.getRoleid());
                            roleMenuElementNew.setMenuid(menuElementDto.getMenuid());
                            roleMenuElementNew.setElementid(elementid);
                            roleMenuElementsList.add(roleMenuElementNew);
                        }
                    }
                }
            }

            Constants.platformApiCacheMap.clear();

            //删除当前用户的所有角色
            roleMenuService.delByRoleId(roleMenuDto.getRoleid());
            roleMenuService.save(roleMenuList);
            roleMenuElementService.del(roleMenuDto.getRoleid());
            roleMenuElementService.save(roleMenuElementsList);
            return this.sucess();
        }catch(Exception e){
            logger.error("保存角色的菜单权限异常", e);
            e.printStackTrace();
            return this.errorJSON("保存角色的菜单权限异常");
        }

    }

}
